import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/style.dart';
import 'package:sp_util/sp_util.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/config/config.dart';
import 'package:yp/router.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/videoplayer/video_player_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../helper.dart';
import 'logic.dart';

class MyPointsPage extends StatelessWidget {
  final logic = Get.put(MyPointsLogic());
  final state = Get.find<MyPointsLogic>().state;

  void _onRefresh() async {
    state.currentPage = 1;
    logic.getMemberPointsTurnover();
    logic.refreshController.refreshCompleted();
  }

  void _onLoading() async {
    state.currentPage++;
    logic.getMemberPointsTurnover();
    logic.refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF4F5F7),
      appBar: AppBar(
        backgroundColor: Config.mainColor,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: Colors.white),
        title: Text(
          "积分明细",
          style: TextStyle(fontSize: 17),
        ),
        centerTitle: true,
      ),
      body: _buildMyPointsPageBody(),
    );
  }

  //  优惠券类型
  Widget _couponType(String typeIndex) {
    var type = '折扣券';
    if (typeIndex == '0') {
      type = '折扣券';
    } else if (typeIndex == '1') {
      type = '现金券';
    } else if (typeIndex == '2') {
      type = '免邮券';
    } else if (typeIndex == '8') {
      type = '兑换券';
    }

    return Container(
      child: Text(
        type,
        style: TextStyle(
          color: Color(0xffa5673f),
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  List<Widget> _newList(dynamic adList) {
    var commonWidgets = List<Widget>();
    for (var item in adList) {
      if (item['adv_type'] == '1') {
        commonWidgets.add(
          Container(
            margin: EdgeInsets.only(bottom: 20.w),
            child: Stack(
              children: <Widget>[
                new Image(
                  width: 750.r,
                  height: 375.r,
                  fit: BoxFit.fill,
                  image: new NetworkImage(
                    item['adv_object_url'],
                  ),
                ),
                item['tag_name'] != null
                    ? Positioned(
                        //方法二
                        right: 20.w,
                        bottom: 20.w,
                        child: new Container(
                          padding: EdgeInsets.only(
                            left: 6.0,
                            right: 6.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          decoration: BoxDecoration(
                            border: Border.all(
                              width: 1,
                              color: Color(0xff708090),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(10),
                            ),
                          ),
                          child: Text(
                            item['tag_name'],
                            style: TextStyle(
                              color: Color(0xff708090),
                              fontSize: 10,
                            ),
                          ),
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        );
      } else if (item['adv_type'] == '2') {
        commonWidgets.add(
          Container(
            margin: EdgeInsets.only(bottom: 20.w),
            child: Stack(
              children: <Widget>[
                new VideoPlayerPlus(
                  VideoPlayerController.network(item['adv_object_url']),
                ),
                item['tag_name'] != null
                    ? Positioned(
                        //方法二
                        right: 20.w,
                        bottom: 20.w,
                        child: new Container(
                          padding: EdgeInsets.only(
                            left: 6.0,
                            right: 6.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          decoration: BoxDecoration(
                            // color: Color(0xff708090),
                            border: Border.all(
                              width: 1,
                              color: Color(0xff708090),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(10),
                            ),
                          ),
                          child: Text(
                            item['tag_name'],
                            style: TextStyle(
                              color: Color(0xff708090),
                              fontSize: 10,
                            ),
                          ),
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        );
      } else if (item['adv_type'] == '3') {
        Map<String, dynamic> user = jsonDecode(item['style_num_name']);
        user.forEach((key, value) {
          value[0]['shop_num_id'] = key;
          item['mdms_style'] = value[0];
        });
        commonWidgets.add(
          InkWell(
            onTap: () {
              String itemNumId =
                  item['mdms_style']['default_item_num_id'].toString();
              String styleNumId = item['mdms_style']['style_num_id'].toString();
              String ecStyleNumId =
                  item['mdms_style']['ec_style_num_id'].toString();
              // String cat1Id = item['mdms_style']['cat1_id']?.toString() ?? '';
              // print('cat1Id---------$cat1Id');
              Get.toNamed(RouteConfig.goodsDetail, arguments: {
                'itemNumId': itemNumId,
                'styleNumId': styleNumId,
                'shopId': item['mdms_style']['shop_num_id'],
                'ecStyleNumId': ecStyleNumId,
                // 'cat1Id': cat1Id,
                'typeIndex': item['mdms_style']['is_pre_sale'] ?? 0,
              });
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w),
              padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 25.w),
              decoration: BoxDecoration(
                  boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 5.0.w)],
                  color: Colors.white,
                  borderRadius: new BorderRadius.circular((20.0.w))),
              child: Column(
                children: [
                  // Container(
                  //   alignment: Alignment.centerLeft,
                  //   margin: EdgeInsets.only(right: 10.w, bottom: 30.w),
                  //   child: Text(
                  //     item['mdms_style']['title'],
                  //     style: TextStyle(
                  //       color: Color(0xff333333),
                  //       fontWeight: FontWeight.bold,
                  //       fontSize: 32.w,
                  //     ),
                  //   ),
                  // ),
                  Container(
                    constraints: BoxConstraints(minHeight: 250.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          // width: 300.w,
                          child: Image.network(
                            item['mdms_style']['image_default_id'],
                            width: 250.w,
                            height: 220.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(left: 30.w),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    item['mdms_style']['style_num_name'],
                                    style: TextStyle(
                                      color: Color(0xff666666),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 30.w,
                                    ),
                                  ),
                                ),
                                Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 0,
                                            bottom: 0,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                // color: Color(0xff708090),
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(30),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      alignment: Alignment.centerLeft,
                                      margin: EdgeInsets.only(top: 100.w),
                                      child: Text(
                                        '¥ ${item['mdms_style']['price']}',
                                        style: TextStyle(
                                          color: Color(0xff666666),
                                          fontWeight: FontWeight.bold,
                                          fontSize: 30.w,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '4') {
        commonWidgets.add(
          InkWell(
            onTap: () {
              // 拼团
              if (item['results'][0]['ecactivity_classify'] == 1) {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null,
                  'shop_id': item['results'][0]['ec_shop_num_id']
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 2) {
                // 限时秒杀
                Map<String, dynamic> map = {'results': item['results']};
                Get.toNamed(
                  RouteConfig.seckillHome,
                  parameters: {},
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 3) {
                // 预售
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'pic_url': '',
                  'linktype': 12,
                  'linktarget': item['results'][0]['ecactivity_id'],
                  'shop_id': item['results'][0]['ec_shop_num_id'],
                };
                Get.toNamed(
                  RouteConfig.preSaleActive,
                  arguments: {'model': map},
                );
              } else {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              }
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w),
              child: Stack(
                children: <Widget>[
                  item['results'].length != 0
                      ? new Image(
                          image: new NetworkImage(
                            item['activity_cover_url'],
                          ),
                        )
                      : Container(),
                  item['tag_name'] != null && item['results'].length != 0
                      ? Positioned(
                          //方法二
                          right: 20.w,
                          bottom: 20.w,
                          child: new Container(
                            padding: EdgeInsets.only(
                              left: 6.0,
                              right: 6.0,
                              top: 2.0,
                              bottom: 2.0,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(
                                width: 1,
                                color: Color(0xff708090),
                              ),
                              borderRadius: BorderRadius.all(
                                Radius.circular(30),
                              ),
                            ),
                            child: Text(
                              item['tag_name'],
                              style: TextStyle(
                                color: Color(0xff708090),
                                fontSize: 10,
                              ),
                            ),
                          ),
                        )
                      : Container(),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '5') {
        var data = jsonDecode(item['coupon_num_name']);
        commonWidgets.add(
          Container(
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics() ,
              shrinkWrap: true,
              itemExtent: 160.0,
              itemCount: data.length,
              itemBuilder: (ctx, index) {
                return InkWell(
                  onTap: data[index]['cover_url'] == null
                      ? () {}
                      : () {
                          toast('领取中...');
                          var params = {
                            "use_platform": 2,
                            "coupon_num_id":
                                data[index]['series'].toString(), //券编码
                            "usr_num_id": SpUtil.getInt('empeNumId'),
                            "access_token": SpUtil.getString('token'),
                            "relation": "领券中心",
                            "qsource": 301,
                            "relation_indate": "永久有效",
                            "user_num_id": SpUtil.getInt('empeNumId'),
                          };
                          Api.getCoupon(params).listen(
                            (event) {
                              toastDismissOther(event['message']);
                            },
                          );
                        },
                  child: Container(
                    constraints: new BoxConstraints.expand(
                      height: 134.0,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.0),
                      image: DecorationImage(
                        image: NetworkImage("${data[index]['cover_url']}"),
                        fit: BoxFit.cover,
                      ),
                      color: Color(0xfff2c899),
                    ),
                    margin: EdgeInsets.only(bottom: 20.w, top: 20.w),
                    child: Row(
                      children: data[index]['cover_url'] != null
                          ? []
                          : [
                              Container(
                                width: 100.0,
                                margin: EdgeInsets.only(right: 20.w),
                                padding: EdgeInsets.only(left: 20.w),
                                child: Column(
                                  children: [
                                    Container(
                                      height: 30,
                                    ),
                                    data[index]['coupontype'] == '0'
                                        ? Row(
                                            children: [
                                              Text(
                                                '${data[index]['face_value'] / 10}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                              Text(
                                                '折',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Row(
                                            children: [
                                              Text(
                                                '¥',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                              Text(
                                                '${data[index]['face_value']}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                            ],
                                          ),
                                    Container(
                                      margin: EdgeInsets.only(top: 4.0),
                                      child: _couponType(
                                          data[index]['coupontype']),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 20.w,
                                            bottom: 20.w,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(10),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      // width: 400.w,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            margin:
                                                EdgeInsets.only(bottom: 10.0),
                                            padding: EdgeInsets.only(top: 18.w),
                                            child: Text(
                                              data[index]['title'],
                                              style: TextStyle(
                                                color: Color(0xff000000),
                                                fontSize: 18.0,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            child: item['start_time'] != null &&
                                                    item['end_time'] != null
                                                ? _getDate(item['start_time'],
                                                    item['end_time'])
                                                : Container(),
                                          ),
                                          InkWell(
                                            onTap: () {
                                              toast('领取中...');
                                              var params = {
                                                "use_platform": 2,
                                                "coupon_num_id": data[index]
                                                        ['series']
                                                    .toString(), //券编码
                                                "usr_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                                "access_token":
                                                    SpUtil.getString('token'),
                                                "relation": "领券中心",
                                                "qsource": 301,
                                                "relation_indate": "永久有效",
                                                "user_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                              };
                                              Api.getCoupon(params).listen(
                                                (event) {
                                                  toastDismissOther(
                                                      event['message']);
                                                },
                                              );
                                            },
                                            child: Container(
                                              padding: EdgeInsets.only(
                                                left: 10.0,
                                                right: 10.0,
                                                top: 4.0,
                                                bottom: 8.0,
                                              ),
                                              margin:
                                                  EdgeInsets.only(bottom: 20.w),
                                              decoration: BoxDecoration(
                                                color: Color(0xffa5673f),
                                                borderRadius:
                                                    BorderRadius.circular(20.0),
                                              ),
                                              child: Text(
                                                '立即领取',
                                                style: TextStyle(
                                                  color: Color(0xffffffff),
                                                  fontSize: 16,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                    ),
                  ),
                );
              },
            ),
          ),
        );
      }
    }
    return commonWidgets;
  }

  Widget _getDate(start, end) {
    var startTime = start.split(" ")[0];
    var endTime = end.split(" ")[0];
    return Container(
      // width: 300.w,
      margin: EdgeInsets.only(bottom: 10.0),
      child: Text(
        '有效期 $startTime -- $endTime',
        style: TextStyle(
          color: Color(0xff333333),
        ),
      ),
    );
  }

  Widget _buildMyPointsPageBody() {
    return GetBuilder<MyPointsLogic>(
      builder: (logic) {
        return Container(
          child: Column(
            children: [
              Container(
                color: Colors.white,
                padding: EdgeInsets.only(left: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      child: Row(
                        children: [
                          Text("总积分："),
                          Text(
                            logic.state.memberPoints != null
                                ? logic.state.memberPoints.toString()
                                : "",
                            style: TextStyle(
                                color: Config.mainColor, fontSize: 20),
                          )
                        ],
                      ),
                    ),
                    Container(
                        child: TextButton(
                      child: Text(
                        "如何获取？",
                        style: TextStyle(color: Config.mainColor, fontSize: 12),
                      ),
                      onPressed: () => Get.toNamed(RouteConfig.getPointsMethod),
                    ))
                  ],
                ),
              ),
              Container(
                color: Color(0xffF4F5F7),
                padding: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: () {
                        state.type = 0;
                        logic.update();
                        logic.onRefresh();
                      },
                      child: Text(
                        "全部",
                        style: TextStyle(
                          color:
                              state.type == 0 ? Config.mainColor : Colors.black,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        state.type = 1;
                        logic.update();
                        logic.onRefresh();
                      },
                      child: Text(
                        "已使用",
                        style: TextStyle(
                          color:
                              state.type == 1 ? Config.mainColor : Colors.black,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        state.type = 2;
                        logic.update();
                        logic.onRefresh();
                      },
                      child: Text(
                        "已过期",
                        style: TextStyle(
                          color:
                              state.type == 2 ? Config.mainColor : Colors.black,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                  child: logic.state.memberPointsTurnoverList.length > 0
                      ? Container(
                          child: SmartRefresher(
                            enablePullDown: true,
                            enablePullUp: true,
                            header: CustomHeader(
                              builder:
                                  (BuildContext context, RefreshStatus mode) {
                                return Container(
                                  height: 55.0,
                                  child: Center(
                                      child: CupertinoActivityIndicator()),
                                );
                              },
                            ),
                            footer: CustomFooter(
                              builder: (BuildContext context, LoadStatus mode) {
                                Widget body;
                                if (mode == LoadStatus.idle) {
                                  body = Text("上拉加载更多");
                                } else if (mode == LoadStatus.loading) {
                                  body = CupertinoActivityIndicator();
                                } else if (mode == LoadStatus.failed) {
                                  body = Text("加载失败！点击重试！");
                                } else if (mode == LoadStatus.canLoading) {
                                  body = Text("释放以加载更多");
                                } else {
                                  body = Text("没有更多了");
                                }
                                return Container(
                                  height: 55.0,
                                  child: Center(child: body),
                                );
                              },
                            ),
                            controller: logic.refreshController,
                            onRefresh: _onRefresh,
                            onLoading: _onLoading,
                            child: ListView.separated(
                                itemCount:
                                    logic.state.memberPointsTurnoverList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 20, vertical: 10),
                                    color: Colors.white,
                                    child: Column(
                                      children: [
                                        state.advertising.length > 0 &&
                                                index == 0
                                            ? Column(
                                                children:
                                                    _newList(state.advertising),
                                              )
                                            : Container(),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Container(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Container(
                                                    child: Text(
                                                      logic.state.memberPointsTurnoverList[
                                                              index]["memo"] ??
                                                          "",
                                                    ),
                                                  ),
                                                  Container(
                                                    margin:
                                                        EdgeInsets.only(top: 5),
                                                    child: Text(
                                                      logic.state.memberPointsTurnoverList[
                                                                  index]
                                                              ["last_updtme"] ??
                                                          "",
                                                      style: TextStyle(
                                                          fontSize: 12,
                                                          color: Colors.grey),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            Container(
                                              child: Text(
                                                logic
                                                        .state
                                                        .memberPointsTurnoverList[
                                                            index][
                                                            "reserved_integral"]
                                                        .toString() ??
                                                    "",
                                                style: TextStyle(
                                                    color: Config.mainColor,
                                                    fontSize: 18),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  );
                                },
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return Container(
                                    height: 10,
                                  );
                                }),
                          ),
                        )
                      : Container(
                          child: Center(
                            child: Text("暂无数据"),
                          ),
                        )),
            ],
          ),
        );
      },
    );
  }
}
